package com.bird.component.database

import com.baomidou.mybatisplus.core.mapper.BaseMapper
import com.baomidou.mybatisplus.extension.kotlin.KtQueryWrapper
import com.bird.component.database.model.BaseDO
import com.bird.component.ddd.model.entity.BaseEntity
import com.bird.component.ddd.model.enums.EntityChangeStatus

/**
 * 保存实体
 */
fun <T : BaseEntity, D : BaseDO> BaseMapper<D>.storeEntity(t: T, tToD: (T) -> D) {
    val dataObject = tToD(t)
    when (t.changeStatus) {
        EntityChangeStatus.ADD -> {
            this.insert(dataObject)
            t.id = dataObject.id
        }
        EntityChangeStatus.UPDATE -> this.updateById(dataObject)
        EntityChangeStatus.DELETE -> this.deleteById(dataObject)
        EntityChangeStatus.UN_CHANGE -> Unit
    }

}

inline fun <reified D : Any> BaseMapper<D>.saveValueObjects(newValueObject: List<D>?, deleteWrapper: KtQueryWrapper<D>.() -> KtQueryWrapper<D>){
    //先按照条件删除已存在值对象
    this.delete(KtQueryWrapper(D::class.java).deleteWrapper())
    //如果是空，则不在插入
    if (newValueObject.isNullOrEmpty()) {
        return
    }
    //再插入新的值对象
    newValueObject.forEach { this.insert(it) }

}

